import 'package:enjoy_plus/utils/httpp.dart';
import 'package:enjoy_plus/utils/toast.dart';
import 'package:flutter/material.dart';
import 'package:flutter_html/flutter_html.dart';

class NoticeDetail extends StatefulWidget {
  const NoticeDetail({super.key});

  @override
  State<NoticeDetail> createState() => _NoticeDetailState();
}

class _NoticeDetailState extends State<NoticeDetail> {
  Map notifyDetail = {};
  // 注意事项：获取路由参数不能再 initState 中获取，因为此时路由参数还没准备好。
  @override
  void didChangeDependencies() {
    super.didChangeDependencies();
    // 获取路由参数
    final id = ModalRoute.of(context)?.settings.arguments;
    // 非空判断
    if (id != null) {
      // 通过 as 断言指定类型
      getDetail(id as String);
    } else {
      // 注意：didChangeDependencies 还没渲染界面，所以弹窗需要延迟执行
      Future.delayed(const Duration(seconds: 1), () {
        ToastUtil.showError('获取路由参数失败');
      });
    }
  }

  // 获取详情数据
  getDetail(String id) async {
    final res = await http.get('/announcement/$id');
    setState(() {
      notifyDetail = res['data'];
    });
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      appBar: AppBar(
        title: const Text('公告详情'),
      ),
      body: ListView(
        children: [
          Container(
            padding: const EdgeInsets.all(10),
            child: Column(
              crossAxisAlignment: CrossAxisAlignment.start,
              children: [
                // 知识点： 空值合并运算符 ??，当左侧的操作数为 null 或者 undefined 时，返回其右侧操作数，否则返回左侧操作数。
                Text(
                  notifyDetail['title'] ?? '',
                  style: const TextStyle(
                    fontSize: 18,
                    fontWeight: FontWeight.bold,
                  ),
                ),
                const SizedBox(height: 10),
                Row(
                  mainAxisAlignment: MainAxisAlignment.spaceBetween,
                  children: [
                    Text(
                      notifyDetail['creatorName'] ?? '',
                      style: const TextStyle(color: Colors.grey),
                    ),
                    Text(
                      notifyDetail['createdAt'] ?? '',
                      style: const TextStyle(color: Colors.grey),
                    )
                  ],
                ),
                const SizedBox(height: 10),
                // 内容 使用 Html 组件
                Html(
                  data: notifyDetail['content'] ?? '',
                )
                // Text(notifyDetail['content'])
              ],
            ),
          )
        ],
      ),
    );
  }
}
